package com.ahui.ydd.utils;

import io.jsonwebtoken.*;
import io.jsonwebtoken.security.SignatureException;
import org.apache.commons.lang.StringUtils;

import javax.xml.soap.SAAJResult;
import java.util.Date;
import java.util.Map;

public class JwtUtils {

    //token的有效期1小时
    private static final int TOKEN_TIME_OUT = 3_600;

    //加密KEY
    private static final String TOKEN_SECRET = "c2VjcmV0buibgtgrebvregbertgretgergerdbgvredaghbedarfghbaerhgarehgbaerhgbeahgaerhgaerhgbjikbguiobmbuobulbbbobuboiubguipobguiobg";

    //生成token
    public static String getToken(Map params) {
        long currentTime = System.currentTimeMillis();
        return Jwts.builder()
                .signWith(SignatureAlgorithm.HS512, TOKEN_SECRET)//加密方式
                .setExpiration(new Date(currentTime + TOKEN_TIME_OUT * 1000))//过期时间戳
                .addClaims(params)//指定写入的数据
                .compact();
    }

    /**
     * 获取token中的claims信息
     */
    public static Claims getClaims(String token) {
        return Jwts.parser()
                .setSigningKey(TOKEN_SECRET)
                .parseClaimsJws(token)
                .getBody();
    }

    /**
     * 是否有效 true-有效,false-失效
     */
    public static boolean verifyToken(String token){
        if (StringUtils.isEmpty(token)){
            return false;
        }
        try {
            Claims claims = Jwts.parser()
                    .setSigningKey(TOKEN_SECRET)
                    .parseClaimsJws(token)
                    .getBody();
        } catch (Exception e) {
            return false;
        }
        return true;
    }
}
